import {ScrollView, StyleSheet, Text, ToastAndroid, TouchableOpacity, View} from "react-native";
import React, {useCallback, useState} from "react";
import {ScreenHeader} from "./components/ScreenHeader.tsx";
import ProcessTimeline from "../../components/ProcessTimeline.tsx";
import {ApprovalNodeInfo, ProcessInstanceApi, TaskApi} from "../../api/process.ts";
import {HeadForm} from "./components/HeadForm.tsx";
import {MainForm} from "./components/MainForm.tsx";
import Icon from "react-native-vector-icons/Ionicons";
import {Reason, ReasonType} from "../../components/Reason.tsx";
import {getSealInfo} from "../../api/seal.ts";
import {useFocusEffect} from "@react-navigation/native";
import {useAuthStore} from "../../store/authStore.ts";

export function TodoDetail(item: any) {
    const [processNodes, setProcessNodes] = useState<ApprovalNodeInfo[]>([])
    const [isAccepting, setIsAccepting] = useState<boolean>(false)
    const [isRejecting, setIsRejecting] = useState<boolean>(false)
    const [taskId, setTaskId] = useState<any>()
    const userInfo = useAuthStore((state) => state.userInfo);
    const [status, setStatus] = useState<string>('')
    const [canUpdate, setCanUpdate] = useState<boolean | null>(null)
    const [sealInfo, setSealInfo] = useState(item.route.params.item.applyData);

    useFocusEffect(
        useCallback(() => {
            getSealInfo({id: sealInfo.id}).then(res => {
                setSealInfo(res.data);
            });
            ProcessInstanceApi.getApprovalDetail({
                processInstanceId: sealInfo.processInstanceId
            }).then(response => {
                const resData = response.data as any
                if (response?.code === 0 && resData?.activityNodes) {
                    const found = resData.activityNodes.find((node: any) => node.endTime === null);
                    if (found) {
                        console.log(found.id);
                        if (found.id === "applicantRevise")
                            setCanUpdate(true);
                        else
                            setCanUpdate(false);
                    }
                    setTaskId(resData.todoTask.id)
                    setProcessNodes(resData.activityNodes)
                    setStatus(resData.status)
                } else {
                    setProcessNodes([])
                }
            }).catch(error => {
                console.error('获取流程信息失败:', error)
                setProcessNodes([])
            })
        }, [sealInfo.id])
    );
    const styles = StyleSheet.create({
        bottom: {
            position: 'absolute',
            bottom: 0,
            left: 0,
            right: 0,
            flexDirection: 'row',
            backgroundColor: '#fff',
            borderTopWidth: 1,
            borderTopColor: '#eee',
        },
    })

    return (
        <View style={{backgroundColor: '#f7f7f7', flex: 1}}>
            <ScreenHeader
                navigation={item.navigation}
                title="待办详情"
                rightText="          "
            />

            <ScrollView contentContainerStyle={{paddingBottom: 80}}>
                <HeadForm nickname={userInfo.nickname} sealNumber={sealInfo.sealNumber} status={status}/>
                <MainForm sealInfo={sealInfo} processNodes={processNodes}/>
                <ProcessTimeline activityNodes={processNodes}/>
            </ScrollView>


            {canUpdate !== null && !canUpdate &&
                (<View style={styles.bottom}>
                    <TouchableOpacity
                        style={{
                            flex: 1,
                            flexDirection: 'row',
                            justifyContent: 'center',
                            alignItems: 'center',
                            padding: 16,
                        }}
                        onPress={() => setIsAccepting(true)}
                    >
                        <Icon name={"checkmark-circle-outline"} size={24} color="#28a745"/>
                        <Text style={{marginLeft: 8, color: '#28a745', fontSize: 16}}>同意</Text>
                    </TouchableOpacity>

                    <View style={{width: 1, backgroundColor: '#eee'}}/>

                    <TouchableOpacity
                        style={{
                            flex: 1,
                            flexDirection: 'row',
                            justifyContent: 'center',
                            alignItems: 'center',
                            padding: 16,
                        }}
                        onPress={() => setIsRejecting(true)}
                    >
                        <Icon name={"close-circle-outline"} size={24} color="#dc3545"/>
                        <Text style={{marginLeft: 8, color: '#dc3545', fontSize: 16}}>驳回</Text>
                    </TouchableOpacity>
                </View>)
            }
            {canUpdate !== null && canUpdate &&
                (<View style={styles.bottom}>
                    <TouchableOpacity
                        style={{
                            flex: 1,
                            alignItems: 'center',
                            flexDirection: 'column',
                            justifyContent: 'center',
                            padding: 16,
                        }}
                        onPress={async () => {
                            item.navigation.navigate('CreateSealScreen', {
                                type: "update",
                                info: sealInfo
                            });
                        }}
                    >
                        <Icon name={"create-outline"} size={24} color="#000"/>
                        <Text style={{marginTop: 4}}>修改申请材料</Text>
                    </TouchableOpacity>
                </View>)
            }

            <Reason
                type={ReasonType.ACCEPT}
                visible={isAccepting}
                onClose={() => setIsAccepting(false)}
                onSubmit={async (reason) => {
                    console.log(taskId)
                    const res = await TaskApi.approveTask({
                        id: taskId,
                        reason: reason,
                    })
                    if (res.code === 0) {
                        ToastAndroid.show('审批成功', ToastAndroid.SHORT);
                        item.navigation.goBack();
                    } else {
                        ToastAndroid.show('审批失败，请联系开发者', ToastAndroid.SHORT);
                        item.navigation.goBack();
                    }
                    console.log(res, res.data)
                    setIsAccepting(false);
                }}
            />
            <Reason
                type={ReasonType.REJECT}
                visible={isRejecting}
                onClose={() => setIsRejecting(false)}
                onSubmit={async (reason) => {
                    console.log('驳回理由:', reason);
                    const res = await TaskApi.rejectTask({
                        id: taskId,
                        reason: reason,
                    })
                    if (res.code === 0) {
                        ToastAndroid.show('审批成功', ToastAndroid.SHORT);
                        item.navigation.goBack();
                    } else {
                        ToastAndroid.show('审批失败，请联系开发者', ToastAndroid.SHORT);
                        item.navigation.goBack();
                    }
                    console.log(res, res.data)
                    setIsRejecting(false);
                }}
            />
        </View>
    )
}